package red.lixiang.controller;

import red.lixiang.model.BaseInfo;
import red.lixiang.model.Member;
import red.lixiang.model.WeChatInfo;
import red.lixiang.service.AccountService;
import red.lixiang.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static red.lixiang.base.APPCONST.BACK_URL;
import static red.lixiang.base.APPCONST.MEMBER_INFO;
import static red.lixiang.base.APPCONST.WECHAT_INFO;

@Controller
public class AccountController {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AccountService accountService;


    @GetMapping("/account/showLogin")
    public String showLogin(@RequestParam(required = false)String type) {
        if(type.equals("1")){
            //微信登录而来，有微信号，没有手机号，提示绑定手机号
        }
        return "login";
    }

    @GetMapping("/account/sendVerifyCode/{mobilePhone}")
    @ResponseBody
    public String sendVerifyCode(@PathVariable String mobilePhone) {

        //生成4位随机数,范围是1000-9999
        String verifyCode = String.valueOf(new Random().nextInt(8999) + 1000);
        String verifyMsg = "您的验证码为:" + verifyCode + "（三分钟内有效）";
        System.out.println(verifyMsg);
        SMSUtils.sendSms(mobilePhone, verifyMsg);
        String redisKey = "verifyCode:" + mobilePhone;
        redisTemplate.opsForValue().set(redisKey, verifyCode, 180, TimeUnit.SECONDS);
        return "验证码已发送，请查收";
    }

    @GetMapping("/account/submitLogin")
    @ResponseBody
    public String submitLogin(@RequestParam String mobilePhone,
                              @RequestParam String verifyCode,
                              HttpServletRequest request,
                              HttpServletResponse response) throws IOException {

        WeChatInfo weChatInfo = (WeChatInfo) request.getSession().getAttribute(WECHAT_INFO);

        BaseInfo baseInfo = accountService.submitLoginByVerifyCode(mobilePhone, verifyCode, weChatInfo.getOpenid());

        Member member = (Member) baseInfo.getObject();

        request.getSession().setAttribute(MEMBER_INFO,member);

        String backUrl  = (String) request.getSession().getAttribute(BACK_URL);
        //String fullUrl ="http://wapshop.demengsite.cn"+backUrl;
      //  response.sendRedirect(backUrl);

        return backUrl;
    }
}
